<template>
    <div class="step-page">
        <el-steps :active="active" finish-status="success" class="step_list">
            <el-step title="验证手机号" style="width:45% !important;"></el-step>
            <el-step title="填写账号信息" style="width:45% !important;"></el-step>
            <el-step title="注册成功" style="10%"></el-step>
        </el-steps>
        
        <div v-if="active==1" class="step-one">
            <el-form :model="ruleForm2"  ref="ruleForm2" label-position="left" label-width="0px" class="demo-ruleForm login-container">
                <el-form-item prop="account">
                    <el-input type="text" autofocus v-model="mobile" placeholder="请输入您的手机号" @blur="testFn" class="step_phone"></el-input>
                </el-form-item>
                <div id="testBtn" :class="['w350',!isShow?' mb20' :'']" ref="capt"></div>
                <el-form-item prop="checkPass" v-if="isShow" class="checkPass">
                    <el-input type="password"  v-model="code" placeholder="请输入6位验证码"  style="width:216px;"></el-input>
                    <el-button type="button" @click="sendAuthCode" :class="{btn: true, disabled: isDisabled}" style="width:130px;">{{btnTxt}}</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div v-if="active==2" class="step-two">
          <div class="school_address">添加学校地址</div>
          <el-button type="primary" @click="dialogVisible = true">{{schoolList.length>0?"继续添加":"添加"}}</el-button>
          <ul class="school_list">
            <li v-for='(item,index) in schoolList' :key="index">
                <div class="">
                  <div >
                    <span class="name">{{item.leader_name}}</span>
                     <span class="telphone">{{item.leader_phone}}</span> 
                  </div>
                  <div class="address">{{item.site.province.value+item.site.city.value+item.site.area.value+item.leader_detailAddress}}</div>
                </div>
            </li>
          </ul>
          <!-- tiny/small/large/full -->
          <el-dialog title="新增地址信息" :visible.sync="dialogVisible" :before-close="handleClose"  fullscree='true'  size='normal'>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                  <el-form-item label="负责人姓名" prop="leader_name">
                    <el-input v-model="ruleForm.leader_name" placeholder="请输入负责人姓名"></el-input>
                  </el-form-item>
                  <el-form-item label="联系方式" prop="leader_phone">
                    <el-input v-model="ruleForm.leader_phone" placeholder="请输入联系方式"></el-input>
                  </el-form-item>
                  <el-form-item label="省市区" prop="region" >
                    <el-select   v-model="ruleForm.sheng" @change="choseProvince" placeholder="省级地区">
                        <el-option  v-for="item in province" :key="item.id" :label="item.value" :value="item.id"> </el-option>
                    </el-select>
                    <el-select v-model="ruleForm.shi" @change="choseCity" placeholder="市级地区">
                        <el-option v-for="item in shi1" :key="item.id" :label="item.value" :value="item.id"></el-option>
                    </el-select>
                    <el-select v-model="ruleForm.qu" @change="choseBlock" placeholder="区级地区">
                        <el-option v-for="item in qu1" :key="item.id" :label="item.value" :value="item.id"> </el-option>
                    </el-select>
                  </el-form-item>
                   <el-form-item label="详细地址" prop="leader_detailAddress">
                      <el-input v-model="ruleForm.leader_detailAddress" placeholder="请输入详细地址"></el-input>
                    </el-form-item>
                  <el-form-item class="confirm">
                      <el-button @click="handleClose('ruleForm')">取 消</el-button>
                      <el-button type="primary" @click="submitBtn('ruleForm')">确 定</el-button>
                  </el-form-item>
                </el-form>
          </el-dialog>
        </div>
        <div v-if="active==3" class="step-three">
            <div class="login">
              <div class="success"><i class="el-icon-check sucess_color"></i>恭喜您注册成功</div>
              <div class="time">尊敬的用户，恭喜您注册本网站，{{timeout}}秒后立即登录</div>
            </div>
            <el-button type="primary" @click="$router.push('/login')">立即登录</el-button>
        </div>
        <div class="btn">
            <el-button type="primary" class="btn_next" @click="next" v-if="active!=3">下一步</el-button>
        </div>
    </div>

</template>
<script>
import Address from "../mock/data/map.json";
export default {
  data() {
    return {
      timeout: "3",
      dialogVisible: false, //弹窗
      schoolList: [], //学校列表
      leader_detailAddress: "",
      province: "",
      sheng1: "",
      shi: "",
      shi1: [],
      qu: "",
      qu1: [],
      city: "",
      block: "",
      site: { },

      active: 2,
      logining: false,
      isShow: false,
      pid: this.$route.query.pid,
      typeIndex: 1,
      isDisabled: false,
      btnTxt: "获取验证码",
      userName: "", // 账号
      password: "", // 密码
      mobile: "", // 手机号
      code: "", // 验证码
      result: "", // 验证结果
      ruleForm: {
        leader_name: "", //负责人姓名
        leader_phone: "", //联系方式
        sheng: "", //省份
        shi: "", //市区
        qu: "", //区域
        leader_detailAddress: "" //详细地址
      },
      ruleForm2: {
        account: "",
        checkPass: ""
      },
      rules: {
        leader_name: [
          { required: true, message: "请输入负责人姓名", trigger: "blur" }
        ],
        leader_phone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          { min: 11, max: 11, message: "格式不正确", trigger: "blur" }
        ],
        leader_detailAddress: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ]
      }
    };
  },
  watch: {},
  created() {
    this.getCityData();
  },
  methods: {
    //关闭弹窗
    handleClose(formName) {
      this.dialogVisible = false;
      // this.site = {};
      // this.leader_name = "";
      // this.leader_phone = "";
      // this.leader_detailAddress = "";
      this.ruleForm.sheng = "";
      this.ruleForm.shi = "";
      this.ruleForm.qu = "";
      this.$refs[formName].resetFields();
    },
    //下一步
    next() {
      if (this.active == 1 && this.code != "") {
        this.checkPass();
      } else if (this.active == 2) {
        this.active = 3;
        let time = setInterval(() => {
          this.timeout--;
          console.log(this.timeout);
          if (this.timeout == 0) {
            this.$router.push("/login");
            clearInterval(time);
          }
        }, 1000);
      } else if (this.active == 3) {
      }
    },
    //验证滑动解锁
    async testFn() {
      let self = this;
      if (!self.$fn.isMobilePhone(this.mobile)) {
        self.$message({
          type: "error",
          message: `请您输入正确的手机号`
        });
        return;
        self.$refs.capt.innerHTML = "";
      } else {
        self.$post({ url: `/geet/code/${self.mobile}`, data: {} }).then(res => {
          if (res.code === "0") {
            self.$refs.capt.innerHTML = "";
            let data = JSON.parse(res.data);
            let handler = function(captcha) {
              captcha.appendTo("#testBtn");
              window.gt = captcha;
              captcha.onSuccess(() => {
                self.result = captcha.getValidate();
                self.isShow = true;
                self.sendAuthCode();
                setTimeout(() => {
                  self.$refs.capt.innerHTML = "";
                }, 1000);
              });
              captcha.onError(error => {
                self.$message.error({
                  message: error
                });
                captcha.reset();
              });
            };
            window.initGeetest(
              {
                gt: data.gt,
                challenge: data.challenge,
                new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
                offline: !data.success, // 表示用户后台检测极验服务器是否宕机，一般不需要关注
                product: "popup", // 产品形式，包括：float(点击汉字)，popup(滑动)
                width: "100%"
              },
              handler
            );
          }
        });
      }
    },
    // 手机号登录
    async mobileLogin() {
      let self = this;
      if (!self.result) {
        self.$message({
          type: "error",
          message: "请您完成验证!"
        });
        return;
      }
      let res = await self.$post({
        url: "/user/login/mobile",
        data: {
          mobile: self.mobile,
          validateCode: self.code,
          challenge: self.result.geetest_challenge,
          seccode: self.result.geetest_seccode,
          validate: self.result.geetest_validate
        }
      });
      if (res.status === "SUCCESS") {
        self.$store.commit("setToken", res.data.token);
        self.$store.commit(
          "setNickName",
          res.data.member.nikeName || res.data.member.userName
        );
        localStorage.setItem("hasPassword", res.data.hasPassword);
        localStorage.setItem("hasPayPassword", res.data.hasPayPassword);
        self.$fn.addImFile();
        if (res.code === "1008") {
          // 未设密码
          self.$router.push({
            path: "/setPassword"
          });
        } else {
          // 已设置过密码
          self.$router.push({
            path: "/"
          });
        }
      } else {
        self.testFn();
        self.result = "";
        self.$message({
          type: "error",
          message: res.msg
        });
      }
    },
    // 发送验证码
    async sendAuthCode() {
      console.log("验证码");
      let self = this;
      if (!self.$fn.isMobilePhone(this.mobile)) {
        this.$message({
          type: "error",
          message: `请您输入正确的手机号！`
        });
        return;
      }
      self.isDisabled = true;
      let time = 120;
      let setInter = setInterval(() => {
        time--;
        self.btnTxt = `发送验证码(${time})`;
        if (time <= 0) {
          self.btnTxt = "获取验证码";
          self.isDisabled = false;
          clearInterval(setInter);
          setInter = null;
        }
      }, 1000);

      let res = await self.$get({
        url: `/user/getRegisterCode/${self.mobile}`
      });
      if (res.status === "SUCCESS" && res.code === "0") {
        this.$message({
          type: "success",
          message: `已成功发送验证码到您手机，请查收！`
        });
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
      }
    },
    //验证是否通过
    async checkPass() {
      this.active = 2;
    },
    // 加载china地点数据，三级
    async getCityData() {
      var that = this;
      var data = Address;
      that.province = [];
      that.city = [];
      that.block = [];
      // 省市区数据分类
      for (var item in data) {
        if (item.match(/0000$/)) {
          //省
          that.province.push({
            id: item,
            value: data[item],
            children: []
          });
        } else if (item.match(/00$/)) {
          //市
          that.city.push({ id: item, value: data[item], children: [] });
        } else {
          //区
          that.block.push({ id: item, value: data[item] });
        }
      }
      // 分类市级
      for (var index in that.province) {
        for (var index1 in that.city) {
          if (
            that.province[index].id.slice(0, 2) ===
            that.city[index1].id.slice(0, 2)
          ) {
            that.province[index].children.push(that.city[index1]);
          }
        }
      }
      // 分类区级
      for (var item1 in that.city) {
        for (var item2 in that.block) {
          if (
            that.block[item2].id.slice(0, 4) === that.city[item1].id.slice(0, 4)
          ) {
            that.city[item1].children.push(that.block[item2]);
          }
        }
      }
    },
    // 选省
    choseProvince: function(e) {
      for (var index2 in this.province) {
        if (e === this.province[index2].id) {
          console.log(this.province[index2]);
          this.sheng1 = this.province[index2].value;
          this.shi1 = this.province[index2].children;
          this.ruleForm.shi = this.province[index2].children[0].value;
          this.qu1 = this.province[index2].children[0].children;
          this.ruleForm.qu = this.province[
            index2
          ].children[0].children[0].value;
          this.site.province = this.province[index2];
          this.site.city = this.province[index2].children[0];
          this.site.area = this.province[index2].children[0].children[0];
          this.E = this.qu1[0].id;
        }
      }
    },
    // 选市
    choseCity: function(e) {
      for (var index3 in this.city) {
        if (e === this.city[index3].id) {
          this.ruleForm.shi = this.city[index3].value;
          this.qu1 = this.city[index3].children;
          this.ruleForm.qu = this.city[index3].children[0].value;
          this.site.city = this.city[index3];
          this.site.area = this.city[index3].children[0];
          this.E = this.qu1[0].id;
        }
      }
    },
    // 选区
    choseBlock: function(e) {
      for (var index4 in this.qu1) {
        if (e === this.qu1[index4].id) {
          this.site.area = this.qu1[index4];
        }
      }
    },
    //确定
    submitBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.schoolList.unshift({
            leader_name: this.ruleForm.leader_name,
            leader_phone: this.ruleForm.leader_phone,
            leader_detailAddress: this.ruleForm.leader_detailAddress,
            site: this.site
          });
          this.dialogVisible = false;
          this.handleClose(formName);
          return this.schoolList;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.step-page {
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-border-radius: 5px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 900px;
  padding: 35px 35px 35px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;

  .step_list {
    el-step {
      width: 50% !important;
    }
    el-step.step2 {
      width: 10% !important;
    }
  }
  .step-one {
    width: 350px;
    margin: 22px auto 0;
    .checkPass {
      margin: 0;
    }
    .el-form-item {
      margin: 0;
    }
    .mb20 {
      margin-top: 22px;
    }
  }
  .step-two {
    width: 659px;
    margin: 22px auto 0;
    .school_address {
      font-size: 18px;
      margin-bottom: 22px;
    }
    .leader_name {
      margin-bottom: 10px;
    }
    .leader_phone,
    .leader_address,
    .leader_detailAddress {
      margin: 10px 0;
    }
    .confirm {
      text-align: center;
      margin-left: -100px;
    }
    .school_list{
      margin-left:150px;
      width: 450px;
      li{
        margin: 10px 0;
        padding: 15px;
        border: 1px solid #dddddd;
        .telphone{
          margin-left: 20px;
        }
        .address{
          margin-top: 20px;
        }
      }
    }
  }
  .step-three {
    width: 350px;
    margin: 22px auto 0;
    text-align: center;
    .login {
      .success {
        font-size: 30px;
        // margin: 20px 0;
        padding: 20px 0;
        border-bottom: 1px dotted #ddd;
        .sucess_color {
          color: green;
        }
      }
      .time {
        margin: 30px 0;
      }
    }
  }
  .btn {
    text-align: center;
    margin-top: 22px;
    .btn_next {
      width: 350px;
    }
  }
}
</style>

